<#if needHeadAndBottom != 'no'>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <#include "/pubHeadStyleTree.html">
</head>
<body>
</#if>
<div class="layui-btn-container" style="position: absolute;left: 47%;bottom: 0;">
    <#if hideBtn != 'yes'>
        <button class="layui-btn layui-btn-danger return">关闭</button>
    </#if>
</div>
<div class="formPreview templateDetail layui-form" style="height: 70%;overflow: auto;">

</div>

<script>
    var formKey = '${formKey}';
    <#if needHeadAndBottom != 'no'>
    layui.config({
        base: serverPath.formPath + staticPath.formPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index', 'setter', 'ice', 'form', 'element', 'layer', 'slider', 'colorpicker', 'form', 'table', 'totalFilter', 'propsHandle','commons'], function () {
    <#else>
        layui.use(['setter', 'ice', 'form', 'element', 'layer', 'slider', 'colorpicker', 'form', 'table', 'totalFilter', 'propsHandle','commons'], function () {
    </#if>
        // -----常量声明----------
        var $ = layui.$,
            setter = layui.setter,  // 配置信息
            layer = layui.layer,
            ice = layui.ice,
            propsHandle = layui.propsHandle,
            form = layui.form,
            commons = layui.commons,
            defProps = {
                viewMould: serverPath.formPath + '/form/formDef/view/formDesign/moulds/', // 组件模块 存放文件 *****
                initCss: [
                    'style/forms/grid/grid1',
                    'style/forms/grid/grid2',
                    'style/forms/grid/grid3',
                    'style/forms/template/tag',
                    'style/forms/template/text',
                    'style/forms/template/table',
                    'style/forms/template/textArea',
                    'style/forms/template/radioOption',
                    'style/forms/template/date',
                    'style/forms/template/button',
                    'style/forms/template/uploadFile',
                    'style/forms/template/richText',
                    'style/forms/template/select',
                    'style/forms/template/checkOption',
                    'style/forms/template/dataLexi',
                    'style/forms/template/uploadImg',
                    'style/forms/template/selector',
                    'style/forms/formDevise',
                    'style/forms/dragLay',
                    'style/forms/formPreview'
                ],
                formAreaInfo: 'html',
                temDate: '.temDate',
                uploadFileBtn: '.uploadFileBtn',
                uploadImgBtn: '.uploadImgBtn',
                richTextArea: '.richTextArea',
                selectInput: '.selectInput',
                radioOptionCont: '.radioOptionCont',
                dataLexiTree: '.dataLexiTree',
                selectorBtn: '.selectorBtn'
            },
            temQuery = new propsHandle(); // 实例化模板功能部分

        // init 模板部分渲染
        ice.loadCss(defProps.initCss);

        //判断附件和图片是否是主表里面的元素
        function getUploadFileIsMain(subData, obj) {
            var flag = true;
            for (var p = 0; p < subData.length; p++) {
                var subTableName = subData[p].tableName;
                var tableClass = "temTable " + subTableName + " subFormTable";
                if ($(obj).parents("table ." + tableClass).length > 0) {
                    flag = false;
                }
            }
            return flag;
        }

        var permission;
        $.ajax({
            url: serverPath.formPath + setter.formLinkPath + 'dataTemplate/detailData?alias=' + formKey,
            dataType: 'json',
            data: {"id": '${id}'},
            success: function (result) {
                if (commons._filterRecord(result)) {
                    $(".templateDetail").append(result.data.form);
                    var mainData = result.data.mainFields;
                    var subData = result.data.subFields;
                    permission = result.data.permission;
                    //回显下拉选项的值
                    $(".temSelectCont").each(function () {
                        var value = $(this).attr("val");
                        $(this).val(value);
                    });
                    //回显时候需要在选择器的input上加上ids的值
                    $(".selectorInfo").each(function () {
                        var inputObj = $(this).children();
                        var name = $(this).children().attr("name").split(":");
                        var selectorId = name[2] + "id";
                        inputObj.val(mainData[name[2].toLocaleLowerCase()]);
                        inputObj.attr("ids", mainData[selectorId.toLocaleLowerCase()]);
                    });

                    $("textarea[name^='m:'].textAreaInput").each(function () {
                        var value = $(this).text();
                        var reg=new RegExp("<br/>","g");
                        value = value.replace(reg,"\r\n");
                        $(this).text(value);
                    });

                    //富文本回显
                    $("div[name^='m:'].richTextCont").each(function () {
                        var name = $(this).attr("name").split(":");
                        var fieldName = name[2];
                        $(this).find("textarea").text(mainData[fieldName.toLocaleLowerCase()]);
                    });

                    //回显radio 单选按钮的值
                    $(".radioOptionCont").each(function () {
                        var name = $(this).attr("name").split(":");
                        var fieldName = name[2];
                        $(this).find('input:radio').each(function () {
                            if ($(this).val() == mainData[fieldName.toLocaleLowerCase()]) {
                                $(this).prop('checked', true);
                            }
                        })
                    });
                    //回显复选的值
                    $(".checkOptionCont").each(function () {
                        var name = $(this).attr("name").split(":");
                        var fieldName = name[2];
                        $(this).find('input:checkbox').each(function () {
                            var fieldVal = mainData[fieldName.toLocaleLowerCase()];
                            if (fieldVal != null && fieldVal.indexOf($(this).val()) > -1) {
                                $(this).prop("checked", true);
                            }
                        })
                    });

                    //回显数据字典的值
                    $("input[name^='m:'].dataLexiVal").each(function () {
                        var name = $(this).attr("name").split(":");
                        var fieldName = name[2];
                        if($(this).attr("dictype")==="0"){
                            $(this).parents(".lexiTree").next().find("option").each(function (ind,elem) {
                                if($(elem).text() === mainData[fieldName]) {
                                    $(elem).attr("selected", true);
                                }
                            });
                        }else{
                            $(this).prev().text(mainData[fieldName.toLocaleLowerCase()]);
                        }
                    });

                    //回显文件上传
                    $(".uploadFileList").each(function () {
                        var name = $(this).attr('name');
                        var fieldName = name.replace(/.*:/, '');
                        var flag = getUploadFileIsMain(subData, $(this));
                        if (flag) {
                            if (mainData[fieldName.toLocaleLowerCase()] != "" && mainData[fieldName.toLocaleLowerCase()] != undefined) {
                                var fileIdArray = JSON.parse(mainData[fieldName.toLocaleLowerCase()]);
                                for (var i = 0; i < fileIdArray.length; i++) {
                                    var str = '<li fileId=' + fileIdArray[i]["fileid"] + '><p onclick="downFile(this)">' + fileIdArray[i]["name"] + '</p><i class="layui-icon layui-icon-delete deleteFile" ></i></li>';
                                    $(this).append(str);
                                }
                            }
                        }
                    });

                    //回显图片上传
                    $(".uploadImgList").each(function () {
                        var name = $(this).attr('name');
                        var fieldName = name.replace(/.*:/, '');
                        var flag = getUploadFileIsMain(subData, $(this));
                        if (flag) {
                            if (mainData[fieldName.toLocaleLowerCase()] != "" && mainData[fieldName.toLocaleLowerCase()] != undefined) {
                                var fileIdArray = JSON.parse(mainData[fieldName.toLocaleLowerCase()]);
                                if (fileIdArray.length > 0) {
                                    for (var i = 0; i < fileIdArray.length; i++) {
                                        var str = '<li fileId=' + fileIdArray[i] + '><div class="fileByImg"><img src="' + serverPath.formPath + setter.sysLinkPath + 'attachFile/getFileById?fileId=' + fileIdArray[i] + '" /></div><i class="layui-icon layui-icon-delete deleteFile" ></li>'
                                        $(this).append(str);
                                    }
                                }
                            }
                        }
                    });

                    if (subData) {
                        processSubData(subData);
                    }
                    temQuery.initTemEvent(defProps, serverPath, setter);


                    //根据当前登录人密级查询表单密级列表
                    $.ajax({
                        type: 'post',
                        dataType: 'json',
                        url: serverPath.systemPath + setter.sysLinkPath + "dictionary/listFilterByUserSecret",
                        data: {'nodeKey': 'sjmj'},
                        success: function (result) {
                            $("select[name='fileLevel']").html("");
                            $.each(result.data, function (index, objVal) {
                                //业务数据密级下拉框重新赋值
                                $("select[name^='m:'][name$='dataPrivacyLevel']").append("<option value=" + objVal.itemValue + ">" + objVal.itemName + "</option>");
                                //附件上传控件密级下拉框重新赋值
                                $("select[name='fileLevel']").append("<option value=" + objVal.itemValue + ">" + objVal.itemName + "</option>");
                            });
                            $("select[name^='m:'][name$='dataPrivacyLevel']").val(1);
                                //业务数据密级赋值
                                $(".temSelectCont").each(function () {
                                    var value = $(this).attr("val");
                                    $(this).val(value);
                                });
                                //附件密级赋值
                                $(".uploadFileList").each(function () {
                                    var name = $(this).attr('name');
                                    var fieldName = name.replace(/.*:/, '');
                                    if (mainData[fieldName.toLocaleLowerCase()] != "" && mainData[fieldName.toLocaleLowerCase()] != undefined) {
                                        var fileIdArray = JSON.parse(mainData[fieldName.toLocaleLowerCase()]);
                                        if (fileIdArray.length > 0) {
                                            for (var i = 0; i < fileIdArray.length; i++) {
                                                $(this).prev().children("select").val(fileIdArray[i]["fileLevel"]);
                                            }
                                        }
                                    }
                                });
                            //子表附件密级赋值
                            for (var i = 0; i < subData.length; i++) {
                                var subTableName = subData[i].tableName;
                                var dataList = subData[i].dataList;
                                var inputName = "s:" + subTableName;
                                for (var j = 0; j < dataList.length; j++) {
                                    var trObjs = $("." + subTableName + " tr.temSpace");
                                    var jsonObj = dataList[j];
                                    for (var key in jsonObj) {
                                        var attrName = inputName + ":" + key;
                                        var ulObj = $(trObjs[j + 2]).children().find("ul[name='" + attrName + "']");
                                        var objVal = jsonObj[key];
                                        if (ulObj.length > 0) {
                                            var fileIdArray = JSON.parse(objVal);
                                            for (var g = 0; g < fileIdArray.length; g++) {
                                                ulObj.prev().children("select").val(fileIdArray[g]["fileLevel"]);
                                            }
                                        }
                                    }
                                }
                            }
                            form.render();
                        }
                    });

                    $("input[name^='m:'].dataLexiVal").each(function () {
                        var name = $(this).attr("name").split(":");
                        var fieldName = name[2];
                        if($(this).attr("dictype")==="0"){
                            $(this).parents(".lexiTree").next().find("option").each(function (ind,elem) {
                                if($(elem).text() === mainData[fieldName]) {
                                    $(elem).attr("selected", true);
                                }
                            });
                        }
                    });
                    if (subData) {
                        for (var i = 0; i < subData.length; i++) {
                            var subTableName = subData[i].tableName;
                            var dataList = subData[i].dataList;
                            var inputName = "s:" + subTableName;
                            for (var j = 0; j < dataList.length; j++) {
                                var trObjs = $("." + subTableName + " tr.temSpace");
                                var jsonObj = dataList[j];
                                for (var key in jsonObj) {
                                    var attrName = inputName + ":" + key;
                                    var inputObj = $(trObjs[j + 2]).children().find("input[name='" + attrName + "']");
                                    var objVal = jsonObj[key];

                                    if (inputObj.length > 0) {
                                        if (inputObj.hasClass("dataLexiVal")) {
                                            if(inputObj.attr("dictype")==="0"){
                                                inputObj.parents(".lexiTree").next().find(".lexiSelectCont option").each(function (ind,elem) {
                                                    if($(elem).text() === objVal) {
                                                        $(elem).attr("selected", true);
                                                    }
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    form.render();
                } else {
                    window.parent.layer.alert(result.msg);
                }

            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.alert("预览失败！" + XMLHttpRequest.status);
            }
        });

        //子表数据回显
        function processSubData(subData) {
            //按钮隐藏 input select变成disabled
            $(".subOptState").children().attr("style", "display: none");
            $(".addFormTr").attr("style", "display: none");
            $(".deleteFile").attr("style", "display: none");
            $("input").attr("disabled", "disabled");
            $("textarea").attr("disabled", "disabled");
            $("select").attr("disabled", "disabled");
            $(".uploadImgBtn").attr("style","display: none");
            $(".uploadFileBtn").attr("style", "display: none");
            $(".selectorBtn").attr("style", "display: none");
            $(".dataLexiPanel").attr("style", "pointer-events:none");
            setTimeout(function () {
                $(".richTextCont").each(function () {
                    $(this).find("iframe").contents().find("body").attr("contenteditable",false);
                });
            },0)

            for (var h = 0; h < subData.length; h++) {
                var subTableName = subData[h].tableName;
                var dataList = subData[h].dataList;
                for (var k = 0; k < dataList.length; k++) {
                    if (k > 0) {
                        var cloneTr = $("." + subTableName + " tr.temSpace");
                        var trLength = cloneTr.length;
                        $(cloneTr[trLength - 1]).clone().appendTo("." + subTableName);
                        var cloneTr = $("." + subTableName + " tr.temSpace");
                        //新增的序号赋值
                        var index = cloneTr.length-2;
                        $(cloneTr[cloneTr.length-1]).find("div.temTag").text(index);
                        //radio的input name赋值name="zdxan_2"
                        var radioDiv = $(cloneTr[cloneTr.length-1]).find("div.radioOptionCont");
                        radioDiv.find('input:radio').each(function () {
                            var attrName = $(this).attr("name");
                            var indexStr = "_"+(index-1).toString();
                            var newIndexStr = "_"+index.toString();
                            if(attrName.indexOf(indexStr) > -1){
                                attrName= attrName.replace(indexStr,newIndexStr);
                            }else{
                                attrName= attrName+newIndexStr;
                            }
                            $(this).attr("name",attrName);
                        })
                    }
                }
            }
            for (var i = 0; i < subData.length; i++) {
                var subTableName = subData[i].tableName;
                var dataList = subData[i].dataList;
                var inputName = "s:" + subTableName;
                for (var j = 0; j < dataList.length; j++) {
                    var trObjs = $("." + subTableName + " tr.temSpace");
                    var jsonObj = dataList[j];
                    for (var key in jsonObj) {
                        var attrName = inputName + ":" + key;
                        var inputObj = $(trObjs[j + 2]).children().find("input[name='" + attrName + "']");
                        var selectObj = $(trObjs[j + 2]).children().find("select[name='" + attrName + "']");
                        var divObj = $(trObjs[j + 2]).children().find("div[name='" + attrName + "']");
                        var ulObj = $(trObjs[j + 2]).children().find("ul[name='" + attrName + "']");
                        var objVal = jsonObj[key];
                        if (selectObj.length > 0) {
                            $(selectObj).val(objVal);
                        }
                        if (inputObj.length > 0) {
                            $(inputObj).val(objVal);
                            //选择器input上赋上属性ids
                            if (inputObj.hasClass("selectorInput")) {
                                var selectorId = key + "id";
                                inputObj.attr("ids", jsonObj[selectorId]);
                            }
                            if (inputObj.hasClass("dataLexiVal")) {
                                if(inputObj.attr("dictype")==="0"){
                                    inputObj.parents(".lexiTree").next().find(".lexiSelectCont option").each(function (ind,elem) {
                                        if($(elem).text() === objVal) {
                                            $(elem).attr("selected", true);
                                        }
                                    });
                                }else{
                                    inputObj.prev().text(objVal);
                                }
                            }
                        }
                        //附件 图片
                        if (ulObj.length > 0) {
                            var fileIdArray = JSON.parse(objVal);
                            for (var g = 0; g < fileIdArray.length; g++) {
                                var str = '<li fileId=' + fileIdArray[g]["fileid"] + '><p>' + fileIdArray[g]["name"] + '</p><i class="layui-icon layui-icon-delete deleteFile" ></i></li>';
                                if (ulObj.hasClass("uploadImgList")) {
                                    str = '<li fileId=' + fileIdArray[g] + '><div class="fileByImg"><img src="' + serverPath.formPath + setter.sysLinkPath + 'attachFile/getFileById?fileId=' + fileIdArray[g] + '" /></div><i class="layui-icon layui-icon-delete deleteFile" ></li>'
                                }
                                ulObj.append(str);
                            }
                        }
                        if (divObj.length > 0) {
                            divObj.find('input:checkbox').each(function () {
                                if (objVal != null && objVal.indexOf($(this).val()) > -1) {
                                    $(this).prop("checked", true);
                                }
                            });
                            //处理单选按钮
                            divObj.find('input:radio').each(function () {
                                if ($(this).val() === objVal) {

                                    $(this).prop('checked', true);
                                }
                            })
                            //富文本
                            divObj.find('textarea').text(objVal);
                        }
                        var textareaObj = $(trObjs[j + 2]).children().find("textarea[name='" + attrName + "']");
                        var regExp=new RegExp("<br/>","g");
                        var textVal = objVal.replace(regExp,"\r\n");
                        $(textareaObj).val(textVal);
                    }
                }
            }
            form.render();
        }


        // 初始化模板功能
        temQuery.initTem({
            selectorBtn: defProps.selectorBtn,
            selectorTemPath: setter.views + defProps.viewMould
        });

        // 子表初始化事件
        temQuery.initSubEvent(defProps, serverPath, setter);

        var index = parent.layer.getFrameIndex(window.name);
        $('.return').click(function () {
            parent.layer.close(index);
        })

    })
</script>
<#if needHeadAndBottom != 'no'>
</body>
</html>
</#if>

